package data

import (
	"context"
	"github.com/go-kratos/kratos/v2/log"
	"go-skeleton/app/admin/service/internal/biz"
	"go-skeleton/app/admin/service/internal/data/ent"
	"go-skeleton/app/admin/service/internal/data/ent/adminmenu"
	"go-skeleton/app/admin/service/internal/data/ent/schema"
	"go-skeleton/pkg/util/tool"
	"strconv"
)

type AdminMenuRepo struct {
	data *Data
	log  *log.Helper
}

func NewAdminMenuRepo(data *Data, logger log.Logger) biz.AdminMenuRepo {
	return &AdminMenuRepo{
		data: data,
		log:  log.NewHelper(log.With(logger, "module", "data/admin/menu")),
	}
}

func (r *AdminMenuRepo) Save(ctx context.Context, m *ent.AdminMenu) (*ent.AdminMenu, error) {
	return r.data.db.AdminMenu.
		Create().
		SetMenuType(m.MenuType).
		SetPath(m.Path).
		SetName(m.Name).
		SetComponent(m.Component).
		SetRedirect(m.Redirect).
		SetTitle(m.Title).
		SetIsLink(m.IsLink).
		SetIsHide(m.IsHide).
		SetIsKeepAlive(m.IsKeepAlive).
		SetIsAffix(m.IsAffix).
		SetIsIframe(m.IsIframe).
		SetIcon(m.Icon).
		SetParentID(m.ParentID).
		SetParentPath(m.ParentPath).
		SetSort(m.Sort).
		Save(ctx)
}

func (r *AdminMenuRepo) Update(ctx context.Context, m *ent.AdminMenu) (*ent.AdminMenu, error) {
	return r.data.db.AdminMenu.
		UpdateOneID(m.ID).
		SetMenuType(m.MenuType).
		SetPath(m.Path).
		SetName(m.Name).
		SetComponent(m.Component).
		SetRedirect(m.Redirect).
		SetTitle(m.Title).
		SetIsLink(m.IsLink).
		SetIsHide(m.IsHide).
		SetIsKeepAlive(m.IsKeepAlive).
		SetIsAffix(m.IsAffix).
		SetIsIframe(m.IsIframe).
		SetIcon(m.Icon).
		SetParentID(m.ParentID).
		SetParentPath(m.ParentPath).
		SetSort(m.Sort).
		Save(ctx)
}

func (r *AdminMenuRepo) FindByID(ctx context.Context, id int64) (*ent.AdminMenu, error) {
	return r.data.db.AdminMenu.Get(ctx, id)
}

func (r *AdminMenuRepo) List(ctx context.Context, names []string) ([]*ent.AdminMenu, error) {
	menu, err := r.data.db.AdminMenu.Query().Where(adminmenu.NameIn(names...)).All(ctx)
	if err != nil {
		return nil, err
	}

	ids := make([]int64, 0)
	for _, m := range menu {
		ids = append(ids, m.ID)
		for _, pid := range m.ParentPath {
			tmpPid, _ := strconv.ParseInt(pid, 10, 64)
			ids = append(ids, tmpPid)
		}
	}
	return r.data.db.AdminMenu.Query().Where(adminmenu.IDIn(tool.Int64SliceUniq(ids)...)).Where(adminmenu.MenuTypeEQ(schema.MenuType)).Order(ent.Asc(adminmenu.FieldID), ent.Asc(adminmenu.FieldSort)).All(ctx)
}

func (r *AdminMenuRepo) ListAll(ctx context.Context) ([]*ent.AdminMenu, error) {
	return r.data.db.AdminMenu.Query().Order(ent.Asc(adminmenu.FieldID), ent.Asc(adminmenu.FieldSort)).All(ctx)
}

func (r *AdminMenuRepo) Del(ctx context.Context, id int64) error {
	return r.data.db.AdminMenu.DeleteOneID(id).Exec(ctx)
}
